﻿
Imports System.Data
Imports System.Data.SqlClient
Partial Class Sistema_HogaresConsulta
    Inherits System.Web.UI.Page
    Dim editar As Boolean
    Dim Idv As Integer
    Public link As Boolean
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CompareValidator3.ValueToCompare = Date.Now().ToShortDateString

        If Page.IsPostBack = False Then
            If String.IsNullOrEmpty(Request.QueryString.Item("idHogar")) = False Then
                hdIdHogar.Value = Request.QueryString.Item("idHogar")
            End If
            llenarCombos()
            traerPersonas()
            cargarbeneficiarios()
            beneficiarios()
            personasregistradasvsfaltantes()
            visitasregistradas()
            traervisitaspersona()
            cargarestado()

        End If

        If hdIdHogar.Value <> 0 Then
            editar = True
            traerHogar()
        End If
        Municipio._ddlDepartamento.Enabled = False
        Municipio._ddlMun.Enabled = False
        listas()
    End Sub

    Sub traervisitaspersona()
        'Try


        Using bd As New BdHogaresDataContext

            Dim a = From i In bd.Web_Visitas
                    Where (i.idHogar = hdIdHogar.Value)
                    Select i.idvisita, i.Visita

            ddvisitas.DataSource = a
            ddvisitas.DataValueField = "idvisita"
            ddvisitas.DataTextField = "Visita"
            ddvisitas.DataBind()
            ddvisitas.SelectedIndex = ddvisitas.Items.Count - 1
            ddvisitas.Enabled = False

        End Using
        'Catch ex As Exception

        'End Try
    End Sub
    Sub cargarestado()
        'Psicosocial
        lblfamiliar.Text = "No diligenciado"
        lblcomunitario.Text = "No diligenciado"
        Try
            Using bd As New BdHogaresDataContext

                Dim a = From i In bd.Web_ModuloPsicosocialFamiliars
                              Where i.idHogar = hdIdHogar.Value And i.idvisita = ddvisitas.SelectedValue
                              Select i.rb16ExpresionAfecto

                Dim dato = a.First
                If dato > 0 Then
                    lblfamiliar.Text = "OK"
                End If
            End Using
        Catch ex As Exception
            lblfamiliar.Text = "No diligenciado"
        End Try

        Try
            Using bd As New BdHogaresDataContext

                Dim a = From i In bd.Web_ModuloPsicosocialComunitarios
                              Where i.idhogar = hdIdHogar.Value And i.idvisita = ddvisitas.SelectedValue
                              Select i.rbparticipacionescenariosfamilia

                Dim dato = a.First
                If dato > 0 Then
                    lblcomunitario.Text = "OK"
                End If
            End Using
        Catch ex As Exception
            lblcomunitario.Text = "No diligenciado"
        End Try
    End Sub
    Sub cargarbeneficiarios()
        Using bd As New BdHogaresDataContext
            Dim a = bd.GetPersonasbyIdHogarBeneficiarios(hdIdHogar.Value)
            ddbeneficiarios.DataSource = a
            ddbeneficiarios.DataValueField = "idpersona"
            ddbeneficiarios.DataTextField = "Nombres"
            ddbeneficiarios.DataBind()

         

        End Using
    End Sub
#Region "cargar Datos"
    Sub traerPersonas()
        Using bd As New BdHogaresDataContext
            Dim a = bd.GetPersonasbyIdHogar(hdIdHogar.Value)
            grdResultados.DataSource = a
            grdResultados.DataBind()
        End Using

    End Sub


    Sub llenarCombos()
        Using cnn As New SqlConnection(ConfigurationManager.ConnectionStrings("CNNdb").ConnectionString)
            cnn.Open()
            LlenarItems(rbLocalizacion, "Ubicacion", cnn)
            LlenarItems(rbformacionprofesional, "formacionprofesional", cnn)
            cnn.Close()
        End Using
    End Sub

    Sub LlenarItems(ByVal objeto As Object, ByVal pregunta As String, ByRef cnn As SqlConnection)
        If pregunta = "sino" Then : objeto.Items.Add(New ListItem("Sí", 1)) : objeto.Items.Add(New ListItem("No", 2)) : Exit Sub : End If
        Using drDatos As SqlDataReader = Funciones.TraerListas(pregunta, cnn)
            With objeto
                .DataSource = drDatos
                .DataTextField = "nombreopcion"
                .DataValueField = "valoropcion"
                .DataBind()
            End With
        End Using
    End Sub

    Sub listas()
        Dim rbl As RadioButtonList
        rbl = CType(rbformacionprofesional, RadioButtonList) : For Each li As ListItem In rbl.Items : li.Attributes.Add("onclick", "frbformacionprofesional()") : Next
        rbl.Dispose()
        rbl = Nothing
        'CType(txtfechadediligenciamiento, TextBox).Attributes.Add("onBlur", "ftxtfechadediligenciamiento()")
    End Sub

    Sub traerHogar()
        Using bd As New BdHogaresDataContext

            Dim a = From i In bd.Web_FormularioIdentificacionHogars
                      Where i.idHogar = hdIdHogar.Value
                      Select i
            Dim hogar As New Web_FormularioIdentificacionHogar
            hogar = a.FirstOrDefault()
            txtCodigoCoba.Text = hogar.CodCoba
            Municipio.cargarMunicipio(hogar.Municipio)
            rbLocalizacion.SelectedValue = hogar.Localizacion
            txtDireccion.Text = hogar.Direccion
            txtCorregimiento.Text = hogar.Corregimiento
            txtVereda.Text = hogar.Vereda
            TxtPersonasConformanHogar.Text = hogar.Numerodepersonashogar
            TxtNombreContacto.Text = hogar.NombredelContacto
            TxtCelularContacto.Text = hogar.CelulardeContacto
            TxtindicativoContacto.Text = hogar.indicativoContacto
            TxtFijoContacto.Text = hogar.FijoContacto
            ddlNombreProyecto.Text = hogar.Web_Proyecto.CodigoProyecto

            'SAMUEL CODIGO PARA MOSTRAR EL NOMBRE DEL BARRIO Y DE LA COMUNA EN EL LABEL TXTBARRIO Y TXTCOMUNA
            If rbLocalizacion.SelectedValue = 1 Then
                Dim b = From j In bd.Barrio
                        Where j.CodBarrio = hogar.Barrio
                        Select j

                Dim bar As New Barrio
                bar = b.FirstOrDefault
                txtBarrio.Text = bar.Barrio
                txtComuna.Text = bar.CodComuna
            Else
                txtBarrio.Text = ""
                txtComuna.Text = ""
            End If

            ' FIN SAMUEL

        End Using

    End Sub
#End Region
#Region "Metodos"
    Sub guardar()
        Dim hogar As New Web_FormularioIdentificacionHogar
        hogar.CodCoba = txtCodigoCoba.Text
        hogar.Municipio = Municipio.CodMunicipio
        hogar.Localizacion = rbLocalizacion.SelectedValue
        hogar.Direccion = txtDireccion.Text
        hogar.Barrio = txtBarrio.Text
        hogar.Comuna = txtComuna.Text
        hogar.Corregimiento = txtCorregimiento.Text
        hogar.Vereda = txtVereda.Text
        hogar.Numerodepersonashogar = TxtPersonasConformanHogar.Text
        hogar.NombredelContacto = TxtNombreContacto.Text
        hogar.CelulardeContacto = TxtCelularContacto.Text
        hogar.indicativoContacto = TxtindicativoContacto.Text
        hogar.FijoContacto = TxtFijoContacto.Text
        hogar.idProyecto = ddlNombreProyecto.Text

        Using bd As New BdHogaresDataContext
            bd.Web_FormularioIdentificacionHogars.InsertOnSubmit(hogar)
            bd.SubmitChanges()
            bd.registrarLog(Context.User.Identity.Name, 4, Request.CurrentExecutionFilePath)
        End Using

    End Sub

    Sub actualizar()
        Using bd As New BdHogaresDataContext
            Dim a = From i In bd.Web_FormularioIdentificacionHogars
                      Where i.idHogar = hdIdHogar.Value
                      Select i

            Dim hogar As New Web_FormularioIdentificacionHogar
            hogar = a.FirstOrDefault()

            hogar.CodCoba = txtCodigoCoba.Text
            hogar.Municipio = Municipio.CodMunicipio
            hogar.Localizacion = rbLocalizacion.SelectedValue
            hogar.Direccion = txtDireccion.Text
            hogar.Barrio = txtBarrio.Text
            hogar.Comuna = txtComuna.Text
            hogar.Corregimiento = txtCorregimiento.Text
            hogar.Vereda = txtVereda.Text
            hogar.Numerodepersonashogar = TxtPersonasConformanHogar.Text
            hogar.NombredelContacto = TxtNombreContacto.Text
            hogar.CelulardeContacto = TxtCelularContacto.Text
            hogar.indicativoContacto = TxtindicativoContacto.Text
            hogar.FijoContacto = TxtFijoContacto.Text
            hogar.idProyecto = ddlNombreProyecto.Text

            bd.SubmitChanges()
            bd.registrarLog(Context.User.Identity.Name, 4, Request.CurrentExecutionFilePath)

        End Using


    End Sub
#End Region
#Region "Enventos controles"


    Protected Sub btnGuardar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGuardar.Click
        If editar = True Then
            actualizar()
        Else
            guardar()
        End If
    End Sub



    Protected Sub btnCancelar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        Response.Redirect("Inicio.aspx")
    End Sub
#End Region

    Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
        Try
            Using db As New BdHogaresDataContext
                Dim a = From i In db.Web_Visitas
                        Where (i.idHogar = hdIdHogar.Value)
                        Select i
                Dim visita = a.FirstOrDefault.idvisita
            End Using
            Response.Redirect("ModuloPersonas.aspx?idHogar=" & hdIdHogar.Value)
        Catch ex As Exception
            Response.Write("<script>alert('Debe registrar alguna visita antes de ingresar un miembro de hogar')</script>")
            Exit Sub
        End Try
    End Sub

    Sub personasregistradasvsfaltantes()
        Using db As New BdHogaresDataContext
            Dim a = db.usp_personasregistradasvsrequeridas(hdIdHogar.Value)
            grdpersona.DataSource = a
            grdpersona.DataBind()

        End Using

    End Sub

    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        panelvisitas.Visible = True
        Using bd As New BdHogaresDataContext

            Dim a = From i In bd.Web_Parametros
                    Where (i.Categoria = "visitas")
                    Select i.NombreOpcion, i.ValorOpcion

            ddvisita.DataSource = a
            ddvisita.DataValueField = "NombreOpcion"
            ddvisita.DataTextField = "NombreOpcion"
            ddvisita.DataBind()

            Dim b As New usp_GetSiguienteVisitaResult()
            b = bd.usp_GetSiguienteVisita(hdIdHogar.Value).FirstOrDefault


            If IsNothing(b) = False Then
                ddvisita.SelectedValue = b.NombreOpcion
            End If
            ddvisita.Enabled = False

        End Using

    End Sub

    Protected Sub btnRegistrar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRegistrar.Click
        agregarvisita()
        panelvisitas.Visible = False
        visitasregistradas()
        traervisitaspersona()
        cargarestado()
    End Sub
    Sub agregarvisita()

        Using bd As New BdHogaresDataContext ' Verifica si ya se registro la misma visita para el hogar
            Dim a = From i In bd.Web_Visitas
                      Where i.idHogar = hdIdHogar.Value And i.Visita = ddvisita.SelectedValue
                      Select i

            If a.Count > 0 Then
                Response.Write("<script>alert('Ya existe esa visita para el hogar, los datos no se han guardado')</script>")
                Exit Sub
            End If
        End Using


        Dim visita As New Web_Visita
        visita.Visita = ddvisita.SelectedValue
        visita.NombreProfesional = txtNombreprofesional.Text
        visita.Formacionprofesional = rbformacionprofesional.SelectedValue
        visita.FormacionprofesionalOtro = txtformacionprofesional.Text
        visita.FechaDiligenciamiento = txtfechadediligenciamiento.Text
        visita.idHogar = hdIdHogar.Value
        Using bd As New BdHogaresDataContext
            bd.Web_Visitas.InsertOnSubmit(visita)
            bd.SubmitChanges()
            bd.registrarLog(Context.User.Identity.Name, 5, Request.CurrentExecutionFilePath)
        End Using
    End Sub


    Sub visitasregistradas()
        Using db As New BdHogaresDataContext


            'Dim a = From i In db.Web_Visitas
            '        Where (i.idHogar = hdIdHogar.Value)
            '        Select i

            Dim a = db.usp_ListaVisitas(hdIdHogar.Value)
            grdvisitas.DataSource = a
            grdvisitas.DataBind()
        End Using
    End Sub

    Protected Sub grdvisitas_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdvisitas.RowCommand
        If e.CommandName = "borrar" Then
            Using bd As New BdHogaresDataContext
                Dim a = From i In bd.Web_ModuloEducacions
                          Where i.idvisita = e.CommandArgument.ToString
                          Select i.idvisita
                Idv = Idv + a.FirstOrDefault()
            End Using

            Using bd As New BdHogaresDataContext
                Dim a = From i In bd.Web_ModuloSaludComplementarios
                          Where i.idvisita = e.CommandArgument.ToString
                          Select i.idvisita
                Idv = Idv + a.FirstOrDefault()
            End Using

            Using bd As New BdHogaresDataContext
                Dim a = From i In bd.Web_ModuloSaludSexualReproductivas
                          Where i.idvisita = e.CommandArgument.ToString
                          Select i.idvisita
                Idv = Idv + a.FirstOrDefault()
            End Using

            Using bd As New BdHogaresDataContext
                Dim a = From i In bd.Web_ModuloSaludCrecimientoDesarrollos
                          Where i.idvisita = e.CommandArgument.ToString
                          Select i.idvisita
                Idv = Idv + a.FirstOrDefault()
            End Using

            If Idv = 0 Then
                Using bd As New BdHogaresDataContext
                    Dim a As Integer = e.CommandArgument
                    bd.usp_eliminarvisitabyid(a)
                    bd.SubmitChanges()
                End Using
            Else
                Response.Write("<script>alert('No se puede eliminar la visita por que tiene datos registrados')</script>")
            End If

        End If
        visitasregistradas()
        personasregistradasvsfaltantes()
    End Sub



    Protected Sub grdResultados_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdResultados.RowCommand

        If e.CommandName = "borrar" Then
            Using bd As New BdHogaresDataContext
                Dim a = From i In bd.Web_ModuloEducacions
                          Where i.idPersona = e.CommandArgument.ToString
                          Select i.idPersona
                Idv = Idv + a.FirstOrDefault()
            End Using

            Using bd As New BdHogaresDataContext
                Dim a = From i In bd.Web_ModuloSaludComplementarios
                          Where i.idPersona = e.CommandArgument.ToString
                          Select i.idPersona
                Idv = Idv + a.FirstOrDefault()
            End Using

            Using bd As New BdHogaresDataContext
                Dim a = From i In bd.Web_ModuloSaludSexualReproductivas
                          Where i.idPersona = e.CommandArgument.ToString
                          Select i.idPersona
                Idv = Idv + a.FirstOrDefault()
            End Using

            Using bd As New BdHogaresDataContext
                Dim a = From i In bd.Web_ModuloSaludCrecimientoDesarrollos
                          Where i.idPersona = e.CommandArgument.ToString
                          Select i.idPersona
                Idv = Idv + a.FirstOrDefault()
            End Using

            Using bd As New BdHogaresDataContext
                Dim a = From i In bd.web_Novedades
                          Where i.idPersona = e.CommandArgument.ToString
                          Select i.idPersona
                Try
                    Idv = Idv + a.FirstOrDefault()
                Catch

                End Try
            End Using

            If Idv = 0 Then
                Using bd As New BdHogaresDataContext
                    Dim a As Integer = e.CommandArgument
                    bd.usp_eliminarpersonabyid(a)
                    bd.SubmitChanges()
                End Using

            Else
                Response.Write("<script>alert('No se puede eliminar la persona por que tiene datos registrados')</script>")
            End If

        End If

        traerPersonas()
        personasregistradasvsfaltantes()
    End Sub

    Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click

        Dim Datos As New Web_beneficiariosDirecto
        Datos.idPersona = ddbeneficiarios.SelectedValue

        Using bd As New BdHogaresDataContext
            bd.Web_beneficiariosDirectos.InsertOnSubmit(Datos)
            bd.SubmitChanges()
        End Using

        beneficiarios()

    End Sub
    Sub beneficiarios()
        Using bd As New BdHogaresDataContext
            Dim a = bd.GetPersonasbyIdHogarBeneficiariosGrid(hdIdHogar.Value)
            grdBeneficiarios.DataSource = a
            grdBeneficiarios.DataBind()
        End Using
        If ddvisitas.SelectedValue = "" Then
            link = False
        End If
    End Sub

    Protected Sub btnIngresarPsicosocial_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnIngresarPsicosocial.Click


        If Not ddvisitas.SelectedValue = "" Then
            'Solo se puede diligenciar a partir de la visita 1
            If (ddvisitas.SelectedItem.Text = "Levantamiento de información") Then
                CustomValidator1.ErrorMessage = "Solo se puede diligenciar a partir de la visita 1"
                CustomValidator1.IsValid = False
                CustomValidator1.Enabled = True
                btnIngresarPsicosocial.Focus()
                Exit Sub
            End If

            'verificar que ya se haya diligenciado la información de los demás módulos
            Using bd As New BdHogaresDataContext

                Dim a = bd.RPTRevision04InstrumentosIncompletosXhogar(ddvisitas.SelectedItem.Text, hdIdHogar.Value, 0)

                If User.Identity.Name <> "aarias" Then

                    If CInt(a.Single.Personas_con_módulos_no_diligenciados) > 0 Then
                        CustomValidator1.ErrorMessage = "La información de algunos de los módulos de este hogar no están diligenciados. Diligencie toda la información de la visita antes de continuar"
                        CustomValidator1.IsValid = False
                        CustomValidator1.Enabled = True
                        btnIngresarPsicosocial.Focus()
                        Exit Sub
                    End If
                End If
            End Using



            Select Case rbmodulopsicosocial.SelectedValue
                Case 2
                    Response.Redirect("ModuloPsicosocialFamiliar.aspx?idvisita=" & ddvisitas.SelectedValue & "&idpersona=" & hdIdPersona.Value & "&idhogar=" & hdIdHogar.Value)
                Case 3
                    Response.Redirect("ModuloPsicosocialComunitario.aspx?idvisita=" & ddvisitas.SelectedValue & "&idpersona=" & hdIdPersona.Value & "&idhogar=" & hdIdHogar.Value)
                Case 4
                    Response.Redirect("ModuloMetas.aspx?idvisita=" & ddvisitas.SelectedValue & "&idpersona=" & hdIdPersona.Value & "&idhogar=" & hdIdHogar.Value)
            End Select
        End If
    End Sub

    Protected Sub grdBeneficiarios_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdBeneficiarios.RowCommand
        If e.CommandName = "borrar" Then
            Using bd As New BdHogaresDataContext
                bd.eliminarBeneficiarioDirecto(CInt(e.CommandArgument))
                cargarbeneficiarios()
                beneficiarios()
                bd.registrarLog(Context.User.Identity.Name, 5, Request.CurrentExecutionFilePath)
            End Using
        End If
    End Sub
End Class
